package controllers

import (
	"MaternalBaby/api/models"
	"fmt"
	"os/exec"
	"time"

	"github.com/astaxie/beego/cache"
	"github.com/astaxie/beego/orm"

	"github.com/astaxie/beego"
)

var (
	o  orm.Ormer
	bm cache.Cache
)

func init() {
	o = orm.NewOrm()
	bm, _ = cache.NewCache("memory", `{"interval":3600}`)
}

type BaseController struct {
	beego.Controller
	u       models.User
	isLogin bool
}

func (c *BaseController) Prepare() {
	token := c.GetString("Token")
	if token != "" {
		o.QueryTable(c.u).Filter("Token", token).One(&c.u)
	}
	if c.u.Id > 0 {
		c.isLogin = true
	}
}

func (c *BaseController) checkLogin() bool {
	if !c.isLogin {
		c.Fail(2, "必需登录")
	}
	return c.isLogin
}

type MainController struct {
	BaseController
}

func (c *MainController) Get() {
	c.Data["v"] = beego.AppConfig.String("version_code")
	c.TplName = "web/index.html"
}

func (c *MainController) Admin() {
	c.Data["v"] = beego.AppConfig.String("version_code")
	c.TplName = "admin/index.html"
}

func (c *MainController) Callback() {
	c.Ctx.WriteString("母婴助手")
}

func (c *MainController) Update() {
	go func() {
		time.Sleep(1 * time.Second)
		cmd := exec.Command("bash", "../restart.sh")
		err := cmd.Run()
		if err != nil {
			beego.Info(err)
		}
	}()
	c.Success("更新成功" + beego.AppConfig.String("version_code"))
}

func (c *BaseController) Fail(code int, data interface{}) {
	var msg string
	switch data.(type) {
	case string:
		msg = data.(string)
	default:
		msg = fmt.Sprint(data)
	}
	c.Data["json"] = map[string]interface{}{"code": code, "data": msg}
	c.ServeJSON()
}

func (c *BaseController) Success(data interface{}) {
	c.Data["json"] = map[string]interface{}{"code": 0, "data": data}
	c.ServeJSON()
}

func (c *BaseController) EmptyList() {
	c.Success([]string{})
}

func (c *BaseController) Page(data interface{}, qs orm.QuerySeter) {
	total, err := qs.Limit(-1).Offset(0).Count()
	if err != nil {
		c.Fail(2, err)
		return
	}
	c.Data["json"] = map[string]interface{}{"code": 0, "data": data, "total": total}
	c.ServeJSON()
}

func (c *BaseController) Page2(data interface{}, total int) {
	c.Data["json"] = map[string]interface{}{"code": 0, "data": data, "total": total}
	c.ServeJSON()
}
